<template>
  <div id="app-container">
    <ToolboxPanel @templateSelected="handleTemplateSelection" />
    <CanvasPanel />
    <InspectorPanel />
  </div>

  <div class="global-actions">
    <div class="pdf-generator">
      <textarea v-model="dynamicDataStr" placeholder="在此输入JSON动态数据..."></textarea>
      <div class="selected-template-info">
        当前模板: {{ selectedTemplateForGen?.name || '未选择' }}
        <small>{{ selectedTemplateForGen?._id || '' }}</small>
      </div>
      <button @click="generatePdf" :disabled="!selectedTemplateForGen">生成 PDF</button>
    </div>
    
    <button @click="saveTemplate">保存当前画布为模板</button>
  </div>
</template>

<script setup lang="ts">
import ToolboxPanel from './components/ToolboxPanel.vue'
import CanvasPanel from './components/CanvasPanel.vue'
import InspectorPanel from './components/InspectorPanel.vue'
import { useTemplateStore } from './stores/templateStore'
import axios from 'axios'
import { ref } from 'vue'

const store = useTemplateStore()
const dynamicDataStr = ref(`{\n  "name": "张三",\n  "orderId": "123456789"\n}`)

// 用于生成PDF的当前选中模板
const selectedTemplateForGen = ref<any>(null)

// 接收从子组件传递过来的模板选择事件
const handleTemplateSelection = (template: any) => {
    selectedTemplateForGen.value = template;
};

const saveTemplate = async () => {
  if (store.elements.length === 0) {
    alert('画布为空，无法保存！')
    return
  }
  const name = prompt("请输入模板名称:", "我的新模板");
  if (!name) return;

  try {
    await axios.post('http://localhost:4000/api/templates', {
      elements: store.elements,
      name: name,
      page: store.pageSettings, // 【新增】将页面设置一起发送给后端
    })
    alert(`模板 "${name}" 保存成功！请刷新模板列表查看。`)
  } catch (error) {
    console.error('保存模板失败:', error)
    alert('保存模板失败')
  }
}

const generatePdf = async () => {
  if (!selectedTemplateForGen.value) {
    alert('请先从左侧模板列表中选择一个模板！')
    return
  }
  
  let dynamicData;
  try {
    dynamicData = JSON.parse(dynamicDataStr.value)
  } catch (e) {
    alert('JSON数据格式错误！')
    return
  }
  
  try {
    const response = await axios.post('http://localhost:4000/api/generate-pdf', {
      templateId: selectedTemplateForGen.value._id,
      dynamicData: dynamicData,
    }, {
      responseType: 'blob',
    });

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${selectedTemplateForGen.value.name}.pdf`);
    document.body.appendChild(link);
    link.click();
    link.remove();
  } catch (error) {
    console.error('生成PDF失败:', error)
    alert('生成PDF失败')
  }
}
</script>

<style>
/* ... 原有样式保持不变 ... */
#app-container { display: flex; width: 100vw; height: 100vh; }

.global-actions {
  position: absolute;
  top: 1rem;
  right: 20rem; 
  z-index: 20;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  background: white;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.global-actions button {
  padding: 0.5rem 1rem;
  /* ... 其他样式 ... */
}

/* 【新增】PDF 生成器样式 */
.pdf-generator {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  border-bottom: 1px solid #eee;
  padding-bottom: 1rem;
}
.pdf-generator textarea {
  min-width: 250px;
  min-height: 80px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.pdf-generator input {
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>